package util;

import entity.CellEntity;
import entity.ExcelEntity;
import entity.SheetEntity;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbookFactory;

import java.io.*;
import java.util.List;

public class ExcelWriter {

    public static void exportData(List<ExcelEntity> excelEntityList, String exportFileName){
        OutputStream outputStream = null;
        InputStream fis = null;
        Workbook workbook = null;

        try {
            File file = new File(exportFileName);
            if (!file.exists()) {
                file.createNewFile();
                workbook = new XSSFWorkbook();
            } else {
                fis = new FileInputStream(exportFileName);
                workbook = new XSSFWorkbook(fis);
            }

            outputStream = new FileOutputStream(file);

            for (ExcelEntity excelEntity : excelEntityList) {
                for (SheetEntity sheetEntity : excelEntity.getSheets()) {
                    String newSheetName = excelEntity.getFileName() + sheetEntity.getSheetName();
                    Sheet sheet = workbook.getSheet(newSheetName);
                    if (sheet == null) {
                        sheet = workbook.createSheet(newSheetName);
                    }

                    for (CellEntity cellEntity : sheetEntity.getCells()) {
                        Row row = sheet.getRow(cellEntity.getRow());
                        if (row == null) {
                            row = sheet.createRow(cellEntity.getRow());
                        }

                        Cell cell = row.getCell(cellEntity.getColumn());
                        if (cell == null) {
                            cell = row.createCell(cellEntity.getColumn());
                        }

                        cell.setCellValue(cellEntity.getValue());
                    }
                }
            }
            workbook.write(outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
                if (workbook != null) {
                    workbook.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
